﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Koonsoft.HYCRM.DAL;
using Koonsoft.HYCRM.Model;

public partial class SiteMaster : System.Web.UI.MasterPage
{
    private log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!MenuDAL.HasPermission(Page.User.Identity.Name, Request.Url.AbsolutePath))
        {
            logger.Warn(string.Format("{0}试图访问超出权限的页面{1}", Page.User.Identity.Name, Request.Url.AbsolutePath));

            Response.Write("请勿访问不属于您的权限范围内的页面，行为已被记录!");
            Response.End();
            return;
        }

        if (HeadLoginView.FindControl("AccountName") != null)
        {
            var accountName = (Label)HeadLoginView.FindControl("AccountName");

            accountName.Text = new EmpolyeeDAL().GetEmpolyeeInfoByLoginName(Page.User.Identity.Name).Name;
        }

        try { BindMenu(); }
        catch (Exception ex)
        {
            logger.Error("菜单生成异常",ex);
        }



    }

    /// <summary>
    /// 生成菜单树
    /// </summary>
    private void BindMenu()
    {
        TopMenu.Items.Clear();

        var loginName = Page.User.Identity.Name;

        var topMenus = MenuDAL.GetMenusByEmpolyeeID(loginName);

        if (topMenus != null)
        {
            foreach (var menu in topMenus)
            {
                var mi = new MenuItem
                             {
                                 Text = menu.MenuTitle,
                                 NavigateUrl = "#"
                             };

                var subMenus = MenuDAL.GetSubMenusByEmpolyeeID(loginName, menu.MenuID);

                if (subMenus != null && subMenus.Count > 0)
                {
                    foreach (var subMenu in subMenus)
                    {
                        var submi = new MenuItem
                                        {
                                            Text = subMenu.MenuTitle,
                                            NavigateUrl = subMenu.URL
                                        };

                        mi.ChildItems.Add(submi);
                    }
                }

                TopMenu.Items.Add(mi);
            }
        }
    }
}